import type { ApiRes, ArticleComment } from '@/type'
import { http } from '@/utils'
import { makeAutoObservable } from 'mobx'

class CommentStore {
  commentData: ArticleComment
  constructor() {
    makeAutoObservable(this)
    this.commentData = {
      total_count: 0,
      last_id: null,
      end_id: null,
      results: [],
    }
  }
  // 获取评论数据
  getComment = async (type: string, id: string) => {
    const res = await http.get<ApiRes<ArticleComment>>('/comments', {
      params: {
        type, // 'normal'
        source: id, // 文章id
      },
    })
    this.commentData = res.data.data
  }
  // 新增评论
  addComment = async (target: string, content: string) => {
    const res = await http.post('/comments', {
      target,
      content,
    })
    // 乐观更新 更改本地
    console.log('乐观更新')
    this.commentData.results.unshift(res.data.data.new_obj)
  }
  // 评论点赞
  like = async (comment_id: string, is_liking: boolean) => {
    if (is_liking) {
      // 取消点赞
      const item = this.commentData.results.find(
        (item) => item.com_id === comment_id
      )
      if (item) {
        item.is_liking = false
        item.like_count--
      }
      await http.delete(`/comment/likings/${comment_id}`)
    } else {
      // 点赞
      // 取消点赞
      const item = this.commentData.results.find(
        (item) => item.com_id === comment_id
      )
      if (item) {
        item.is_liking = true
        item.like_count++
      }
      await http.post('/comment/likings', {
        target: comment_id,
      })
    }
  }
}

export default CommentStore
